<template>
  <div>
    <text-button v-if="!userInfo"
                 text="登录"
                 :width="100"
                 :height="50"
                 :focusable="focusable"
                 @click="loginClick"/>
    <div v-else
         :clipChildren="false"
         :focusable="focusable"
         :enableFocusBorder="false"
         :focusScale="1.1"
         @click="logoutClick"
    >
      <es-row>
        <img :src="userInfoObj.headImage" style="width:50px;height:50px"/>
        <span style="width: 200px;height:50px;color:black;font-size:32px">{{userInfoObj.nickname}}</span>
      </es-row>
    </div>

  </div>
</template>

<script>
import {useESEventBus, useESLocalStorage} from "@extscreen/es3-core";

const {defineComponent} = require("@vue/runtime-core");
const {useESRouter} = require("@extscreen/es3-router");
const {__CONFIG__} = require("./config/global");
import {ref,computed,watch} from 'vue'
import EsRow from "../components/container/EsRow";

export default defineComponent({
  name: "LoginStatusView",
  components: {EsRow},
  props: {
    focusable:Boolean,
    default:false
  },
  //登陆页面的状态
  setup(props,{emit}){
    const router = useESRouter()
    var esEventBus = useESEventBus();
    var esLocalStorage = useESLocalStorage();
    const userInfo=ref('')
    let userInfoObj=computed({
      get:()=>{
        if (validUserInfo(userInfo.value)){
          return JSON.parse(userInfo.value)
        }
      }
    })
    esLocalStorage.getString(__CONFIG__.userInfoKey).then(res=>{
      if (validUserInfo(res)){
        userInfo.value=res
        __CONFIG__.userInfoObj=JSON.parse(userInfo.value)
        emit('init')
      }
    })
    const loginClick=()=>{
      router.push('login_view')
      esEventBus.on(__CONFIG__.userInfoKey,(res)=>{
        if (validUserInfo(res)){
          userInfo.value=res
          __CONFIG__.userInfoObj=JSON.parse(userInfo.value)
        }
      })
    }
    const logoutClick=()=>{
      router.push('logout_view')
      esEventBus.on(__CONFIG__.userInfoKey,(res)=>{
        userInfo.value=null
        __CONFIG__.userInfoObj=null
      })
    }
    function validUserInfo(userInfo){
      console.log('userInfo',userInfo)
      return userInfo && userInfo.toString().startsWith("{")
        &&userInfo.toString().endsWith("}")
    }
    return {
      loginClick,
      userInfo,
      userInfoObj,
      logoutClick,
    }
  }
})
</script>

<style scoped>

</style>
